package com.ztom.offer.v2;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 二叉搜索树的后序遍历序列
 * <p>
 * https://leetcode.cn/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/
 *
 * @author ZhangTao
 */
public class Code33VerifyPostorder {

    public boolean verifyPostorder1(int[] postorder) {
        return verify(postorder, 0, postorder.length - 1);
    }

    private boolean verify(int[] arr, int l, int r) {
        if (l >= r) {
            return true;
        }

        int root = arr[r];
        // 找到左子树与右子树的划分点
        int t = l;
        while (arr[t] < root) {
            t++;
        }
        // 判断右子树的节点是否都大于 root 节点
        for (int i = t; i < r; i++) {
            if (arr[i] < root) {
                return false;
            }
        }
        return verify(arr, l, t - 1) && verify(arr, t, r - 1);
    }

    public boolean verifyPostorder(int[] postorder) {
        Deque<Integer> stack = new LinkedList<>();
        int root = Integer.MAX_VALUE;
        for (int i = postorder.length - 1; i >= 0; i--) {
            if (postorder[i] > root) {
                return false;
            }

            while (!stack.isEmpty() && stack.peekLast() > postorder[i]) {
                root = stack.pollLast();
            }
            stack.offerLast(postorder[i]);
        }
        return true;
    }
}
